package ru.niir.goodfil.ui;

import ru.niir.goodfil.db.OrderItem;
import ru.niir.goodfil.ui.models.StoreAnsenceModel;
import ru.niir.goodfil.utils.SumFormat;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class StoreChangesReportBean extends PageBean {

    private Date beginDate;

    private Date endDate;

    private List<StoreAnsenceModel> storeAnsenceModels;

    public StoreChangesReportBean() {
        init();
    }

    public void init(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        beginDate = calendar.getTime();
        endDate = new Date();
        storeAnsenceModels = getItems();
    }

    public List<StoreAnsenceModel> getItems(){
        List list;
        list = gf().getStorekeeperAbsence(beginDate, endDate);
        List<StoreAnsenceModel> result = new ArrayList<StoreAnsenceModel>();
        for(Object o : list){
            Object[] arr = (Object[])o;
            int ordersCount = ((BigInteger)arr[0]).intValue();
            long idGood = ((BigInteger)arr[1]).longValue();
            int goodCount = ((BigDecimal)arr[2]).intValue();
            double lossCost = ((Double)arr[3]);
            StoreAnsenceModel model = new StoreAnsenceModel();
            model.setGoodCode(gf().getGoodById(idGood).getCode());
            model.setGoodCount(goodCount);
            model.setLossCost(lossCost);
            model.setOrdersCount(ordersCount);
            result.add(model);
        }
        return result;
    }

    public Date getBeginDate() {
        if(beginDate == null){
            return null;
        }
        else return new Date(beginDate.getTime());
    }

    public void setBeginDate(Date beginDate) {
        if (beginDate != null) {
            this.beginDate = beginDate;
        } else {
            this.beginDate = null;
        }
    }

    public Date getEndDate() {
        if(endDate == null){
            return null;
        }
        else return new Date(endDate.getTime());
    }

    public void setEndDate(Date endDate) {
        if (endDate != null) {
            this.endDate = endDate;
        } else {
            this.endDate = null;
        }
    }

    public List<StoreAnsenceModel> getStoreAnsenceModels() {
        return storeAnsenceModels;
    }

    public void reloadData(){
        setBeginDate(beginDate);
        setEndDate(endDate);
        storeAnsenceModels = getItems();
    }

    public String getTotalSum(){
        double sum = 0;
        for(StoreAnsenceModel model : storeAnsenceModels){
            sum += model.getLossCost();
        }
        return SumFormat.formatSum("###,###,##0.00", sum);
    }
}
